<template>
  <div class="container">
    <el-card>
      <!-- <el-form ref="searchFormRef" :model="searchData">
        <el-form-item prop="dbname" label="数据库名称">
          <el-select v-model="searchData.dbname" placeholder="请选择" class="search-ipt">
            <el-option v-for="item in dblist" :key="item.id" :label="item.dbtitle" :value="item.dbname" />
          </el-select>
          <el-button class="search-btn" type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form> -->
      <div class="table-wrapper">
        <el-table :data="tableData" border style="width: 100%" :row-class-name="rowClassName">
          <el-table-column label="序号" width="60">
            <template #default="scope">
              {{ scope.row.index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" />

          <el-table-column prop="roles" label="角色">
            <template #default="scope">
              <span v-if="scope.row.roles">
                {{ scope.row.roles }}
              </span>
              <span v-else class="error">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="注册时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-tooltip class="box-item" effect="dark" content="授权角色" placement="top">
                <el-icon color="#222" @click="userRole(scope.row)" class="icon"><Edit /></el-icon>
              </el-tooltip>

              <el-tooltip class="box-item" effect="dark" content="重置密码" placement="top">
                <SvgIcon name="reset-pwd" @click="changePwd(scope.row)" class="icon" />
              </el-tooltip>

              <el-tooltip
                class="box-item"
                effect="dark"
                :content="scope.row.enabled ? '点击停用' : '点击启用'"
                placement="top"
              >
                <SvgIcon
                  name="start"
                  color="#00A870"
                  @click="disable(scope.row)"
                  class="icon"
                  v-if="scope.row.enabled"
                />
                <SvgIcon name="stop" color="#999" @click="enable(scope.row)" class="icon" v-else />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper" v-if="paginationData.total > 0">
        <div class="totalCount">共{{ paginationData.total }}项数据</div>
        <el-pagination
          background
          :layout="paginationData.layout"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 角色权限 -->
    <el-dialog v-model="dialogFormVisible" title="修改角色" width="300">
      <el-form :model="form">
        <el-form-item label="角色：">
          <el-checkbox-group v-model="rolesList">
            <el-checkbox label="admin" />
            <el-checkbox label="user" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancle">取消</el-button>
          <el-button type="primary" @click="addTable"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue"
import { ElMessage, ElLoading, ElMessageBox } from "element-plus"
import { getUserList, enableUser, disableUser, addRole, resetPwd } from "@/api/user"
import { formatDateTime } from "@/utils/index"

onMounted(() => {
  getTableData()
})

const paginationData = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  layout: "prev, pager, next"
})
/** 改变当前页码 */
function handleCurrentChange(value) {
  if (paginationData.value.currentPage === value) return
  paginationData.value.currentPage = value
  getTableData()
}

const changePwd = (row) => {
  ElMessageBox.confirm(`是否确认重置用户${row.username}的密码？此操作会导致原密码失效。`, {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const params = {
      username: row.username
    }
    const { code, data } = await resetPwd(params)
    if (code === 200) {
      ElMessage.success(`密码已重置为${data.password}`)
    }
  })
}
const dialogFormVisible = ref(false)
const form = ref({
  name: "",
  data: "",
  dbname: ""
})
const tableData = ref([])

const enable = (para) => {
  ElMessageBox.confirm("确认通过审核吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    enableTr(para)
  })
}
async function enableTr(row) {
  const { code } = await enableUser({ username: row.username })
  if (code === 200) {
    ElMessage.success("用户通过审核，请授权角色")
    // addRoles(row.username, ["user"])
    getTableData()
  }
}
const disable = (para) => {
  ElMessageBox.confirm("停用后，该用户不能登录", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    disbleTr(para)
  })
}
async function disbleTr(row) {
  const { code } = await disableUser({ username: row.username })
  if (code === 200) {
    ElMessage.success("操作成功")
    getTableData()
  }
}

const addRoles = async (name, roles) => {
  const params = {
    username: name,
    roles: roles.join(",")
  }
  const { code } = await addRole(params)
  if (code === 200) {
    ElMessage.success("操作成功")
    getTableData()
  }
}
function rowClassName({ row, rowIndex }) {
  row.index = rowIndex
}
const rolesList = ref([])
const dialogUserName = ref("新增用户")
function userRole(row) {
  dialogUserName.value = row.username
  rolesList.value = row.roles?.split(",")
  dialogFormVisible.value = true
}
function cancle() {
  rolesList.value = []
  dialogFormVisible.value = false
}
async function addTable() {
  addRoles(dialogUserName.value, rolesList.value)
  rolesList.value = []
  dialogFormVisible.value = false
}
async function getTableData() {
  const wrap = document.getElementsByClassName("table-wrapper")[0]
  const loadingInstance = ElLoading.service({
    target: wrap,
    text: "Loading"
  })
  const { code, data } = await getUserList({
    page: paginationData.value.currentPage,
    pageSize: paginationData.value.pageSize
  })
  if (code === 200) {
    tableData.value = data.resultList
    paginationData.value.total = data.totalCount
  }
  loadingInstance.close()
}
</script>
<style lang="scss" scoped>
/* 设置表头背景色 */
::v-deep(.el-table__header-wrapper th) {
  background-color: #f5f5f5; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-weight: bold; /* 加粗字体 */
}
:deep(.sql-editor .el-form-item__content) {
  display: inline-block !important;
  width: 580px;
}
.error {
  color: #e34d59;
}
.icon {
  margin-right: 20px;
  font-size: 16px;
}
.icon:focus {
  box-shadow: none;
  outline: none;
}
.search-btn {
  margin-left: 16px;
}
.sql-editor {
  display: block;
  .box {
    border: 1px solid #ccc;
  }
}
.search-ipt {
  width: 250px;
}
.add-wrap {
  padding: 20px;
  display: flex;
}
.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
